<template>
    <Head>
        <title>{{title}} - 表单录入</title>
    </Head>
    <el-card class="box-card">
        <template #header>
            <el-tabs
                v-model="editableTabsValue"
                class="demo-tabs"
                @tab-change="handleTabChange"
            >
                <el-tab-pane
                    v-for="item in editableTabs"
                    :key="item.name"
                    :label="item.title"
                    :name="item.name"
                />
            </el-tabs>
        </template>
        <el-button type="primary" @click="dialogFormVisible = true">添加线索</el-button>
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column type="index"/>
            <el-table-column prop="date" label="日期" width="180"/>
            <el-table-column prop="name" label="客户昵称" width="100"/>
            <el-table-column prop="phone" label="手机号" width="180"/>
            <el-table-column prop="wechat" label="微信号" width="100"/>
            <el-table-column prop="address" label="现居地" width="100"/>
            <el-table-column prop="remark" label="备注" width="100"/>
            <el-table-column prop="files" label="附件">
                <template #default="scope">
                    <div class="d-inline">
                        <audio controls :src="scope.row.files">
                            <a :href="scope.row.files">
                                Download audio
                            </a>
                        </audio>
                    </div>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <el-dialog v-model="dialogFormVisible" title="添加线索" :before-close="handleDialogClose">
        <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="客户姓名" prop="name" :error="errorField.name" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="客户电话" prop="phone" :error="errorField.phone" :label-width="formLabelWidth">
                <el-input v-model="form.phone" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="微信号" prop="wechat" :error="errorField.wechat" :label-width="formLabelWidth">
                <el-input v-model="form.wechat" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="地址" prop="address" :error="errorField.address" :label-width="formLabelWidth">
                <el-input v-model="form.address" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark" :error="errorField.remark" :label-width="formLabelWidth">
                <el-input v-model="form.remark" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="录音附件"
                          ref="dialogRef"
                          prop="files" :error="errorField.files" :label-width="formLabelWidth">
                <el-upload
                    v-model:file-list="fileList"
                    class="upload-demo"
                    action="/api/clue/files"
                    :limit="1"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarSuccess"
                >
                    <el-button type="primary">上传文件</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            只能上传媒体音频文件.大小不能超过20MB
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit(formRef)">保存</el-button>
      </span>
        </template>
    </el-dialog>
</template>
<script setup>
import {ref, reactive, defineProps, nextTick, onMounted} from 'vue'
import {Head} from '@inertiajs/inertia-vue3'
import axios from 'axios'
import {ElLoading, ElMessage, ElMessageBox} from "element-plus"

console.log("window.location.hash", window.location.hash);
const {id, title, token} = defineProps(['id', 'title', 'token'])
const defaultForm = {
    name: '',
    phone: '',
    wechat: '',
    address: '',
    remark: '',
    files: '',
}
const formRef = ref();
const dialogRef = ref();
const fileList = ref([]);
const editableTabsValue = ref(window.location.hash ? decodeURI(window.location.hash.substring(1)) : '套取')
const dialogFormVisible = ref(false)
const editableTabs = ref([
    {
        title: '套取',
        name: '套取',
        closable: false,
    },
    {
        title: '套取2',
        name: '套取2',
        closable: false,
    },
    {
        title: '套取3',
        name: '套取3',
        closable: false,
    },


]);
const formLabelWidth = '150px';
const form = reactive({...defaultForm});
const errorField = reactive({...defaultForm});
const rules = reactive({
    name: [
        {required: true, message: '请输入客户名称', trigger: 'blur'},
    ],
    address: [
        {required: true, message: '请输入客户所在地', trigger: 'blur'},
    ],
    remark: [
        {required: true, message: '请输入备注', trigger: 'blur'},
    ],
    files: [
        {required: true, message: '上传录音文件', trigger: 'blur'},
    ],
    phone: [
        {required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的客户电话', trigger: 'blur'},
    ],
});
const loading = ref(false);
const tableData = ref([]);

onMounted(async () => {
    await handleGetCurrentData();
})

const handleAvatarSuccess = (res, file) => {
    form.files = res.file_path;
}

const handleGetCurrentData = async () => {
    try {
        let response = await axios.get(`/api/clue/index_buy_clue?id=${editableTabsValue.value}&source=${id}`)
        if (response.data.code === 0) {
            tableData.value = response.data.data;
            ElMessage.success(response.data.msg);
        }
        console.log("response", response);
    } catch (e) {
        ElMessage.error("发生错误,请联系管理员");
        throw e;
    }
}

const beforeAvatarUpload = (file) => {

    const isAudio = /audio/i.test(file.type);
    const isLt20M = file.size / 1024 / 1024 < 20;

    if (!isAudio) {
        ElMessage.error("只能上传媒体格式!");
    }
    if (!isLt20M) {
        ElMessage.error("上传媒体音频大小不能超过 20MB!");
    }
    return isAudio && isLt20M;
}

const submitToServer = async (data) => {
    try {
        let response = await axios.post("/api/clue/store_buy_clue", data, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': token
            }
        })
        if (response.data.code === 0) {
            ElMessage.success(response.data.msg);
            dialogFormVisible.value = false;
            handleGetCurrentData();
        } else {
            ElMessage.error(response.data.msg);
            if (response.data.field) {
                for (const [key, value] of Object.entries(response.data.field)) {
                    ElMessage.error(`${key} : ${value}`)
                    errorField[key] = value;
                }
            }
            console.log("response", response);
        }
        console.log("data", response);

    } catch (e) {
        ElMessage.error("发生错误,请联系管理员");
        throw e;
    }

}

const handleSubmit = async (formEl) => {
    if (!formEl || loading.value) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true;
            const loadingInstance = ElLoading.service({target: dialogRef.value.dialogRef})

            await submitToServer({
                ...form,
                url: editableTabsValue.value,
                source: id,
            })
            nextTick(() => {
                loadingInstance.close()
            })
            loading.value = false;
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

const handleTabChange = async (tab) => {
    window.location.hash = tab;
    await handleGetCurrentData();
}

const handleDialogClose = (done) => {
    if (loading.value)
        return;
    formRef.value.resetFields();
    fileList.value = [];
    done();
}
</script>
<style lang="less">
.box-card {
    margin: 100px 300px;

    .el-card__header {
        padding: 0 20px;
    }
}

.demo-tabs {
    > .el-tabs__content {
        margin: 0;
    }

    .el-tabs__header {
        margin: 0;
        //padding-right: 20px;
    }
}
</style>
